package com.guoj.easyweb.common.exception;

import com.guoj.easyweb.common.utils.ResponseEntity;
import com.guoj.easyweb.common.utils.StatusCode;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理器
 *
 * @author guoj
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(CustomException.class)
	public ResponseEntity handleRRException(CustomException e){
		return new ResponseEntity(false, e.getCode(), e.getMsg());
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public ResponseEntity handlerNoFoundException(Exception e) {
		logger.error(e.getMessage(), e);
		return new ResponseEntity(false, StatusCode.NOHANDLERFOUNDERROR, "路径不存在，请检查路径!");
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public ResponseEntity handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return new ResponseEntity(false, StatusCode.DUPLICATEKEYERROR, "数据库中已存在该记录");
	}

	@ExceptionHandler(ExpiredJwtException.class)
	public ResponseEntity handleExpiredJwtException(ExpiredJwtException e){
		logger.error(e.getMessage(), e);
		return new ResponseEntity(false, StatusCode.ERROR, "token失效，请重新登录!");
	}

	@ExceptionHandler(Exception.class)
	public ResponseEntity handleException(Exception e){
		logger.error(e.getMessage(), e);
		return new ResponseEntity(false, StatusCode.ERROR, "未知异常，请检查日志。");
	}
}
